<template>
  <div class="user-manager">
    <!-- 用户查询表单 -->
    <div class="query-form">
      <el-form
        :inline="true"
        ref="form"
        size="small"
        :model="user"
        class="demo-form-inline"
      >
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="user.userId" placeholder="请输入用ID"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="user.userName" placeholder="请输入用户名称"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="user.state" placeholder="当前状态">
            <el-option label="所有" :value="0"></el-option>
            <el-option label="在职" :value="1"></el-option>
            <el-option label="离职" :value="2"></el-option>
            <el-option label="试用期" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 用户列表 -->
    <div class="base-table">
      <div class="action">
        <el-button type="primary" size="small" @click="handleOpen">新增</el-button>
        <el-button type="danger" size="small" @click="handlePatchDel">批量删除</el-button>
      </div>
      <el-table
        @selection-change="handleSelectionChange"
        size="mini"
        :data="userList"
        style="width: 100%"
      >
        <el-table-column type="selection"> </el-table-column>
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :formatter="item.formatter"
          :width="item.width"
        >
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDel(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        @current-change="handleCurrentChange"
        background
        layout="prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 用户新增编辑弹窗 -->
    <el-dialog title="用户新增" :visible.sync="showModal">
      <el-form :model="userForm" :rules="rules" ref="dialogForm" label-width="100px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName" autocomplete="off" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="userForm.userEmail" autocomplete="off" placeholder="请输入邮箱">
            <template slot="append">@imooc.com</template>
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" >
          <el-input v-model="userForm.mobile" autocomplete="off" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="岗位" >
          <el-input v-model="userForm.job" autocomplete="off" placeholder="请输入岗位"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="userForm.state" placeholder="请选择状态">
            <el-option label="试用期" value="3"></el-option>
            <el-option label="在职" value="1"></el-option>
            <el-option label="离职" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系统角色" >
          <el-select v-model="userForm.roleList" multiple placeholder="请选择系统角色" style="width:100%;">
            <el-option
              v-for="item in roleList"
              :key="item._id"
              :label="item.roleName"
              :value="item._id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门"  prop="deptId">
          <el-cascader
            v-model="userForm.deptId"
            :options="deptList"
            :props="{ checkStrictly: true  , label : 'deptName', value : '_id'}"
            clearable
            style="width:100%;"
            placeholder="请选择部门"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import util from "../utils/utils";
export default {
  name: "",
  data() {
    return {
      user: {
        state: 0,
        pageNum: 1,
        pageSize: 10,
      },
      userForm: {
          action : "",
          userName : "",
          userEmail : "",
          mobile : "",
          job : "",
          state : "",
          roleList : [],
          deptId : []
      },
      roleList: [],
      deptList: [],
      userList: [],
      rules : {
          userName : [
              {required: true, message: "请输入用户名称",trigger:"blur"}
          ],
          userEmail : [
              {required: true, message: "请输入用户邮箱",trigger:"blur"}
          ],
          deptId : [
              {required: true, message: "请选择部门",trigger:"change"}
          ]
      },
      showModal: false,
      checkedUserIds: [],
      total: 0,
      columns: [
        {
          label: "用户ID",
          prop: "userId",
        },
        {
          label: "用户名",
          prop: "userName",
        },
        {
          label: "用户邮箱",
          prop: "userEmail",
        },
        {
          label: "用户角色",
          prop: "role",
          formatter(row, column, value) {
            // 0：系统管理员  1： 普通用户
            let role = {
              0: "超级管理员",
              1: "普通用户",
            };
            return role[value];
          },
        },
        {
          label: "用户状态",
          prop: "state",
          formatter(row, column, value) {
            // 0:所有 1：在职 2：离职 3：试用期
            let state = {
              0: "所有",
              1: "在职",
              2: "离职",
              3: "试用期",
            };
            return state[value];
          },
        },
        {
          label: "注册时间",
          prop: "createTime",
          formatter(row, column, value) {
            return moment.parseZone(value).local().format("YYYY-MM-DD HH:mm:ss");
          },
          width: 180,
        },
        {
          label: "最后登录时间",
          prop: "lastLoginTime",
          formatter(row, column, value) {
            return util.formateDate(new Date(value));
          },
          width: 180,
        },
      ],
    };
  },
  created() {
    //获取用户列表  
    this.getUserList();

    //获取角色列表
    this.getRoleList()

    //获取部门列表
    this.getDeptList()

  },
  methods: {
    //获取用户列表
    async getUserList() {
      let res = await this.userApi.getUserList(this.user);
      console.log(res);
      this.userList = res.list;
      this.total = res.page.total;
    },
    //用户列表分页
    handleCurrentChange(page) {
      this.user.pageNum = page;
      this.getUserList();
    },
    //表单重置
    handleReset(formName) {
      this.$refs[formName].resetFields();
    },
    //表单查询
    handleQuery() {
      this.getUserList();
    },
    //删除单个用户
    async handleDel(row) {
      this.checkedUserIds.push(row.userId);
      let res = await this.userApi.removeUser(this.checkedUserIds);
      this.getUserList();
      this.checkedUserIds = [];
    },
    //删除多个用户
    async handlePatchDel() {
      if (this.checkedUserIds.length == 0) {
        this.$message.error("请选择要删除的用户");
        return;
      }
      let res = await this.userApi.removeUser(this.checkedUserIds);
      this.getUserList();
      this.checkedUserIds = [];
    },
    //得到选中用户的id
    handleSelectionChange(list) {
      let arr = [];
      list.forEach((item, index) => {
        arr.push(item.userId);
      });
      this.checkedUserIds = arr;
    },
    //打开新增弹窗
    handleOpen() {
      this.showModal = true;
      this.userForm.action = "add";
      this.userForm.userEmail += "@imooc.com"
    },
    //调用角色列表接口
    async getRoleList(){
        let res = await this.userApi.getRoleList();
        console.log(res)
        this.roleList = res
    },
    //调用部门列表接口
    async getDeptList(){
        let res = await this.userApi.getDeptList();
        console.log("res=>:",res)
        this.deptList = res
    },
    //提交弹窗表单数据方法
    handleSubmit(){
        this.$refs["dialogForm"].validate(async valid=>{
            if(valid){  
                let res = await this.userApi.addUser(this.userForm);
                this.showModal = false;
                this.getUserList()
            }else{
                return false;
            }
        })
    },
    //编辑用户
    handleEdit(data){
        this.showModal = true;
        this.$nextTick(()=>{
            Object.assign(this.userForm,data);
        })
        this.userForm.action = "edit";
    }
  },
  components: {},
};
</script>

<style scoped></style>
